package com.util.excel;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.io.FileUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;

import java.util.LinkedList;
import java.util.List;

/**
 * @Description: 大数据量写入csv
 * @Author: hechaobo
 * @Date: 2024/5/15
 **/
public class WriterH {
    ExcelWriter build;
    WriteSheet writeSheet;
    List<Object> list=new LinkedList<>();
    public WriterH(String path) {
        FileUtil.mkParentDirs(path);
        build = EasyExcel.write(path).build();
        writeSheet = EasyExcel.writerSheet().build();
    }

    public WriterH(String path, Class<?> cls) {
        FileUtil.mkParentDirs(path);
        build = EasyExcel.write(path).build();
        writeSheet = EasyExcel.writerSheet().head(cls).build();
    }
    public void write(Object ... data) {
        list.add(ListUtil.toList(data));
        if (list.size() == 50000) {
            build.write(list, writeSheet);
            list.clear();
        }
    }
    /**
     * 达到阈值后自动写入
     * @param data
     */
    public void write(Object data){
        list.add(data);
        if(list.size()==50000){
            build.write(list,writeSheet);
            list.clear();
        }
    }
    public void close(){
        build.write(list,writeSheet);
        build.close();
    }
}
